
// licenseKey: 'non-commercial-and-evaluation'

//vConsole = new VConsole()
window.lutil = {
  //obj clone
  objClone : function (oldObj) {
      var newObj = $.extend(true, {}, oldObj);
      return newObj;
  }
  //arr clone
  , arrClone : function(oldArr){
      return [].concat(oldArr);
  }
}

var example1 = document.getElementById('example1');
var redBorder = {left: {width: 2, color: 'red'},right: {width: 2, color: 'red'},top: {width: 2, color: 'red'},bottom: {width: 2, color: 'red'}};
var gErrCells = [] //存储单元格坐标逗号连接起来构成的字符串如 ['1,2','3,4']
var gChangeFlag = false //标记是否改动数据，当切换到新的人员时重置，用于提醒用户保存数据
var iniData = matrix(18,20,'')
var gWS  //WebSocket
var gIsFillOk = false //标识当前自动识别的填写是否ok，是才进入下一行填充，否则一直填充本行
                      //现在并不使用这个功能，而是手动按方向键向下一个单元格，进入下一个输入  

toastr.options = {
  // showDuration: "100",  
  // hideDuration: "100",  
  // timeOut: "2000",  
  // extendedTimeOut: "100"
}

// websocket 连接   //当断开连接的时候，可以重新执行本函数重连，可配合相应的检测机制
function WsConnect() {
    // Connect to Web Socket
    ws = new WebSocket("ws://localhost:9001/");
    // Set event handlers.
    ws.onopen = function() {
        console.log("onopen");
    };
    ws.onmessage = function(e) {
        // e.data contains received string.
        let retData = JSON.parse(e.data) 
        console.log( retData );
        let selCell = hot.getSelectedLast()
        if( !selCell ){
            console.log('接收到识别数据，但没有选中目标单元格')
            return true
        }
        if( !app.beipingrens_id ){
            console.log('没有选中被评人。')
            return true
        }
        let selRowIdx = selCell[2],
            selColIdx = selCell[3];
        for(let r = 0,len=retData.length; r < len; r++) {
            hot.setDataAtCell( selRowIdx, selColIdx+r, retData[r]  )
        }
        if(gIsFillOk){
            hot.selectCell(selRowIdx+1,selColIdx)
        }
    };
    ws.onclose = function() {
        console.log("onclose");
    };
    ws.onerror = function(e) {
        console.log("onerror");
        console.log(e)
    };

}

WsConnect()

var hot = new Handsontable(example1, {
  //data: Handsontable.helper.createSpreadsheetData(50,18),
  data: JSON.parse(JSON.stringify(iniData))  , //matrix(18,20,''), 
  colHeaders: true,
  rowHeaders: true,
  hiddenColumns: true,
  colWidths: 60,
  nestedHeaders: [
    [{label: '评委', colspan: 2},, {label: '能', colspan: 6}, {label: '勤', colspan:5}, {label: '绩', colspan: 5}],
    ['类别','序号', '战略管理', '科学管理', '人力资源管理', '信息处理', '文化管理', '协调外部环境支持', '工作态度', '工作纪律', '工作效率', '工作意识', '工作负荷', '目标达成', '额外任务', '队伍建设', '外部支持', '工作创新']
  ],
  contextMenu: ['row_above', 'row_below', 'remove_row'],
  manualColumnResize: true,
  licenseKey: 'non-commercial-and-evaluation',
  fillHandle: {
    direction: 'vertical',
    autoInsertRow: true
  },
  afterChange: (changes,sources) => {
    gChangeFlag = true;
  },
  beforeChange: (changes) => {
    if(!app.beipingrens_id){
      toastr.error('尚未选中被评人，录入无效')
      return false;
    }
  }
});


hot.addHook('beforeAutofill', (start, end, data) => {
  //实现数字向下自动递增填充 代码来源https://github.com/handsontable/handsontable/issues/5574 
  for(var k = 0; k <= (end.col - start.col); k++) {
    var str = data[0][k],
      matches = str.match(/\d+$/),
      number;

    if (matches) {
      let init = parseInt(matches[0], 10) + 1
      let strInit = data[0][k].replace(matches[0], '')
      data[0][k] = strInit + init
      for(var i = 1; i <= (end.row - start.row); i++) {
        if(!(data[i])) {
          data.push(data[0].slice())
        }
        data[i][k] = strInit + (init + i)
      }
    }
  }
  
});

const customBordersPlugin = hot.getPlugin('customBorders');

// 清除空白行  //在必要时自动调用
function removeEmptyRows(){
    var oldData = hot.getData(); // 获取数据
    var newData = []
    // 去掉空白行
    for(let r = 0,len=oldData.length; r < len; r++) {
      if(!hot.isEmptyRow(r)){
        newData.push(oldData[r])
      }
    }
    hot.loadData(newData)
}

// 增加n行空白行 
function addEmptyRows(n){  //先拷贝旧数据，处理后再loadData进入
    var oldData = hot.getData()
    var newData = oldData.concat( matrix(hot.countCols(),n,'') )
    hot.loadData(newData)
}

var app = new Vue({
  el: '#vue_app',
  data: {
    message: 'Hello!',
    level: "_",
    depts:[
      // {id:"1", type:"1", name:"财务处"},
    ],
    depts_selected_id:'_', //选中第一项‘所有’
    beipingrens:[
      // {id:"1", name:"张三", level:"1", dept_id:"1" },
    ],
    beipingrens_id:null,
  },
  created: function(){
    var that = this;
    //如果没有这句代码，select中初始化会是空白的，默认选中就无法实现
    //this.depts_selected_id = this.depts[0].id;
    //this.beipingrens_id = this.beipingrens[0].id;

    this.$nextTick(function () {

      $.ajax({
          url: "/tables/getInitDatas/",
          method: "POST",
          data: {  },
          dataType: 'json',
      })
      .done(function(data){
          // console.log('done');
          // console.log(data.depts);
          that.depts = data.depts;
          that.beipingrens = data.beipingrens;
          gChangeFlag = false;
      });//$.ajax

    }) //$nextTick
  },
  methods:{
    
    search: function(){
      var that = this
      var data = {
        dept_id: this.depts_selected_id,
        level  : $("#beipingren_level").val()
      }
      $.ajax({
          url: "/tables/getBeipingrens/",
          method: "POST",
          data: data,
          dataType: 'json',
          beforeSend: function(){
            toastr.info("正在加载被评人列表");
          },
      })
      .done(function(data){
          that.beipingrens = data.beipingrens
      });//$.ajax

    },

    // 选中被评人之后的操作  //请求数据，加载表格
    selectBpr: function(id){
      if(this.beipingrens_id==id) return ;
      if( gChangeFlag ){ //如果表格数据被改动过
        if(!confirm('切换被评人将会导致当前尚未保存的数据丢失，确定切换吗?')) return; 
      }
      this.beipingrens_id = id;
      $.ajax({
          url: "/tables/getBeipingrenScores/",
          method: "POST",
          data: {
            id : id
          },
          dataType: 'json',
          beforeSend: function(){
            toastr.info("正在加载被评人评价数据");
          },
      })
      .done(function(data){
          if(data.status!=1){
            toastr.warning(data.info) 
            return 
          }
          //去掉bpr_id字段，也就是第一列
          for(let i=0,len=data.scores.length; i < len; i++) {
            data.scores[i].splice(0,1)
          }
          //加载进表格
          if(data.scores.length){ //有数据的
            hot.loadData(data.scores)
          }else{  //没数据的就加载一个空表
            hot.loadData(JSON.parse(JSON.stringify(iniData)))
            toastr.warning('尚无数据，请录表')
          }
          gChangeFlag = false; //重新标记为新的数据

      });//$.ajax
    },

    // 保存数据到后端  //支持定时调用
    saveScore: function(method){
      if (typeof method =='undefined')  method='hand_save' ; //手动保存
      var tbData = hot.getData(); // 获取数据
      var saveType = method=='hand_save' ?  '手动保存' : '自动保存';
      var errCellCnt = 0
      toastr.info('正在校验数据')
      for(let r = 0,len=tbData.length; r < len; r++) {
        for( let c=0, len=tbData[r].length; c<len; c++){
            //标记错误单元格，计算总数
            var iden = ''+r+','+c
            var isABCD = "0ABCD".indexOf(tbData[r][c]) >= 1 ? true : false  //0的加入是为了避免indexOf('')=0
            if(!tbData[r][c] || tbData[r][c]=='' || (c>1 && !isABCD) ){ //空错误，或者评分列非ABCD
                customBordersPlugin.setBorders( [[r,c]], redBorder )
                errCellCnt ++
                gErrCells.push( iden ) 
            }else if( gErrCells.indexOf(iden)>=0 ){
                customBordersPlugin.clearBorders( [[r,c]]  )
            }
        }
      }
      //如果有错的单元格，提示处理，提示删除空白行（提供一键删除）
      if(errCellCnt){
          toastr.error('有错误的单元格，不允许保存')
          return;
      }
      var tbDataStr = JSON.stringify(hot.getData()); // 获取数据
      var data = {
        scoreStr : tbDataStr,
        id       : app.beipingrens_id,  ///////////////////////// TODO 改成当前人的id app.beipingrens_id
      }
      // 发送到后端 
      $.ajax({
        url: "/tables/postScores/",
        method: "POST",
        data: data,
        dataType: 'json',
        beforeSend: function(){
          toastr.info(`正在${saveType}数据。`);
        },
      })
      .done(function(data){
          if(data.result && data.result=='1'){
            toastr.success(`${saveType}成功。`);
          }else{
            toastr.error(`${saveType}失败。`);
          }
      });//$.ajax

    }

  }

})

// 产生一个矩阵数组，值为固定的可定义
function matrix(m, n, v) {
  var result = []
  for(var i = 0; i < n; i++) {
      result.push(new Array(m).fill(v))
  }
  return result
}



